package leetcode;

import java.util.Arrays;
import java.util.Comparator;

public class LargestNumber {

	public static void main(String[] args) {
		int[] nums = {0, 0, 0};
		LargestNumber object = new LargestNumber();
		// System.out.println(object.largestNumber(nums));
		System.out.println(Integer.parseInt("01"));
	}
	
	//wrong solution
	@Deprecated
	public String largestNumberWrong(int[] nums) {
		if (nums == null || nums.length <= 0) {
			return null;
		}
		String[] numString = new String[nums.length];
		for (int i = 0; i < nums.length; i++) {
			numString[i] = String.valueOf(nums[i]);
		}
		//按照字典序排序后，再串起来是错误的
		//比如3  30  34
		//正确的顺序应该是34330
		//但是如果简单的串起来就是34303
		Arrays.sort(numString);
		StringBuilder builder = new StringBuilder();
		for (int i = nums.length - 1; i >= 0; i--) {
			builder.append(numString[i]);
		}
		return builder.toString();
	}
	
	public String largestNumber(int[] nums) {
		if (nums == null || nums.length <= 0) {
			return null;
		}
		String[] numString = new String[nums.length];
		for (int i = 0; i < nums.length; i++) {
			numString[i] = String.valueOf(nums[i]);
		}
		//如果a.b > b.a
		// b.c > c.b
		//那么 a.b > c.b
		Arrays.sort(numString, new Comparator<String>() {
			@Override
			public int compare(String a, String b) {
				return (a + b).compareTo(b + a);
			}
		});
		StringBuilder builder = new StringBuilder();
		for (int i = nums.length - 1; i >= 0; i--) {
			builder.append(numString[i]);
		}
		//删除前导0
		while(builder.length() > 1 && builder.charAt(0) == '0'){
			builder.deleteCharAt(0);
		}
		return builder.toString();
	}
}
